#!/bin/sh

# Set base environment
BTRFS_DEVICE=sda5
SNAP_ROOT=ArchRoot-dev
SNAP_HOME=ArchHome-dev

sync
sync

mkdir /tmp/btrfs-${BTRFS_DEVICE}

# mount btrfs and snapshot
mount -t btrfs /dev/${BTRFS_DEVICE} /tmp/btrfs-${BTRFS_DEVICE}
if [[ -d /tmp/btrfs-${BTRFS_DEVICE}/${SNAP_ROOT}/var/lib/machines ]]; then
	btrfs subvolume delete /tmp/btrfs-${BTRFS_DEVICE}/${SNAP_ROOT}/var/lib/machines
fi
if [[ -d /tmp/btrfs-${BTRFS_DEVICE}/${SNAP_ROOT} ]]; then
	btrfs subvolume delete /tmp/btrfs-${BTRFS_DEVICE}/${SNAP_ROOT}
fi
if [[ -d /tmp/btrfs-${BTRFS_DEVICE}/${SNAP_HOME} ]]; then
	btrfs subvolume delete /tmp/btrfs-${BTRFS_DEVICE}/${SNAP_HOME}
fi
sync
sync
btrfs subvolume snapshot /tmp/btrfs-${BTRFS_DEVICE}/ArchLinux-root /tmp/btrfs-${BTRFS_DEVICE}/${SNAP_ROOT}
btrfs subvolume snapshot /tmp/btrfs-${BTRFS_DEVICE}/ArchLinux-home /tmp/btrfs-${BTRFS_DEVICE}/${SNAP_HOME}

sed -i "s/ArchLinux-root/${SNAP_ROOT}/g" /tmp/btrfs-${BTRFS_DEVICE}/${SNAP_ROOT}/etc/fstab
sed -i "s/ArchLinux-home/${SNAP_HOME}/g" /tmp/btrfs-${BTRFS_DEVICE}/${SNAP_ROOT}/etc/fstab

sync
sync
sleep 1

umount /tmp/btrfs-${BTRFS_DEVICE}
rmdir /tmp/btrfs-${BTRFS_DEVICE}

echo "Snapshot finished."

update-grub
